package edu.cuc.akkaDay01.demo04;

import akka.actor.OneForOneStrategy;
import akka.actor.Props;
import akka.actor.SupervisorStrategy;
import akka.actor.UntypedActor;
import akka.japi.Function;
import scala.concurrent.duration.Duration;

import java.util.concurrent.TimeUnit;

/**
 * Created by bingruiqi on 2017/9/10.
 */
public class SuperVisor extends UntypedActor {
    @Override
    public void onReceive(Object o) throws Exception {
        if (o instanceof Props) {
            getContext().actorOf((Props) o, "restartActor");
        } else {
            unhandled(o);
        }
    }

    private static SupervisorStrategy supervisorStrategy = new OneForOneStrategy(3, Duration.create(1, TimeUnit.MINUTES), new Function<Throwable, SupervisorStrategy.Directive>() {
        @Override
        public SupervisorStrategy.Directive apply(Throwable throwable) throws Exception {
            if (throwable instanceof ArithmeticException) {
                System.out.println("meeting arithmeticexception");
                return SupervisorStrategy.resume();
            } else if (throwable instanceof NullPointerException) {
                System.out.println("meeting nullpointerexception");
                return SupervisorStrategy.restart();
            } else if (throwable instanceof IllegalArgumentException) {
                System.out.println("meeting illegalargumentexception");
                return SupervisorStrategy.stop();
            } else {
                return SupervisorStrategy.escalate();
            }
        }

    });

    @Override
    public SupervisorStrategy supervisorStrategy() {
        return supervisorStrategy;
    }
}
